package org.eerbaar.lang.expressions;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.eerbaar.lang.Expression;
import org.eerbaar.lang.HasProperties;
import org.eerbaar.lang.HasRuntime;
import org.eerbaar.lang.Values;
import org.eerbaar.lang.runtime.Executor;

public class Loop implements Expression, HasRuntime, HasProperties {

    private Integer start;
    private Integer end;
    private IntVar index;
    private Expression[] statments = new Expression[] {};

    public Loop() {
        //
    }

    public Loop(int start, int end) {
        this.start = start;
        this.end = end;
    }

    public Loop(int start, int end, Expression e) {
        this.start = start;
        this.end = end;
        addStatment(e);
    }

    public void addStatment(Expression e) {
        List<Expression> list = new ArrayList<Expression>();
        list.addAll(Arrays.asList(statments));
        list.add(e);
        statments = list.toArray(new Expression[] {});
    }

    @Override
    public Expression getProperty(String name) {
        if (name.equals("index")) {
            return index;
        }
        return null;
    }

    @Override
    public org.eerbaar.lang.runtime.Runtime getRuntime() {

        return new org.eerbaar.lang.runtime.Runtime() {

            @Override
            public void execute(Executor exec) {

                IntVar i = index;
                if (i == null) {
                    index = new IntVar(start);
                    i = index;
                }
                Integer endVar = end;

                for (; i.getValue() < endVar; i.increment()) {
                    for (Expression expression : statments) {
                        exec.execute(expression);
                    }
                }
            }

            @Override
            public Object getResult() {
                return Values.UNDEF;
            }
        };
    }

}
